package com.game.config.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class BootNettyServer {
    @Resource
    private MessageServerHandler messageServerHandler;
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    public void bind(int port) throws Exception {
        try {
            ServerBootstrap b = new ServerBootstrap();

            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             // 设置通道初始化器，用于初始化子通道
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch){
                     // 获取通道的管道
                     ChannelPipeline p = ch.pipeline();
                     // 添加字符串解码器
                     p.addLast(new StringDecoder());
                     // 添加字符串编码器
                     p.addLast(new StringEncoder());
                     // 添加消息服务器处理器，用于处理业务逻辑
                     p.addLast(messageServerHandler);
                 }
             })
             // 设置服务器通道的选项，如 backlog 长度
             .option(ChannelOption.SO_BACKLOG, 128)
             // 设置子通道的选项，如保持连接
             .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();

            f.channel().closeFuture().sync();
        } finally {
            // 关闭workerGroup和bossGroup，释放资源
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
